import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { FindManyOptions, Repository } from 'typeorm'
import { SysRoleWithDeptEntity } from './entities/role-width-dept.entity'
import { SysRoleEntity } from './entities/role.entity'

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(SysRoleEntity)
    private readonly sysRoleEntityRep: Repository<SysRoleEntity>,
    @InjectRepository(SysRoleWithDeptEntity)
    private readonly sysRoleWithDeptEntityRep: Repository<SysRoleWithDeptEntity>
  ) {}

  async findRoles(where: FindManyOptions<SysRoleEntity>) {
    return await this.sysRoleEntityRep.find(where)
  }

  /**
   * 根据角色 ID 异步查找与之关联的部门 id 列表
   * @return 返回一个 Promise 解析为一个部门 id 的数组
   */
  async findRoleWithDeptIds(roleId: number) {
    // 使用TypeORM的实体仓库查询方法，异步查找与指定角色ID相关联的部门ID。
    const res = await this.sysRoleWithDeptEntityRep.find({
      select: ['deptId'],
      where: {
        roleId: roleId
      }
    })
    // 查询结果包含部门 id 的数组返回
    return res.map((item) => item.deptId)
  }
}
